package com.guigu.qingcheng.method;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guigu.qingcheng.pojo.goods.Goods;
import com.guigu.qingcheng.pojo.goods.TbSku;
import com.guigu.qingcheng.pojo.goods.TbSpu;
import com.guigu.qingcheng.service.GoodsServiceFeign;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class Page {

    @Autowired
    private GoodsServiceFeign goodsServiceFeign;

    private String pagePath = "f:/sj/";

    @Autowired
    private TemplateEngine templateEngine;

    @RabbitListener(queues = "queue.sjym")
    public void onMessage(Message message) {
        String id = new String(message.getBody());
        System.out.println(id);
        //1. 查询商品信息
        Goods goods = goodsServiceFeign.findGoodsById(id);
        //获取spu信息
        TbSpu spu = goods.getTbSpu();
        //获取sku列表
        List<TbSku> skuList = goods.getSkuList();

        //查询商品分类
        List<String> categoryList = new ArrayList<>();
        categoryList.add(goodsServiceFeign.findById2(spu.getCategory1Id()).getName());//一级分类
        categoryList.add(goodsServiceFeign.findById2(spu.getCategory2Id()).getName());//二级分类
        categoryList.add(goodsServiceFeign.findById2(spu.getCategory3Id()).getName());//三级分类

        //sku的地址
        Map<String, String> urlMap = new HashMap<>();
        for(TbSku sku: skuList){
            if("1".equals(sku.getStatus())){
                String specJson = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                urlMap.put(specJson, sku.getId()+".html");
            }
        }


        //2. 批量生成sku页面
        for(TbSku sku: skuList){
            //(1)创建上下文和数据模型
            Context context = new Context();
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("spu", spu);
            dataModel.put("sku", sku);
            dataModel.put("categoryList", categoryList);
            dataModel.put("skuImages", sku.getImages().split(","));//sku图片列表
            dataModel.put("spuImages", spu.getImages().split(","));//spu图片列表
            Map paraItems = JSON.parseObject(spu.getParaItems());// 参数列表
            dataModel.put("paraItems", paraItems);
            Map<String, String> specItems = (Map)JSON.parseObject(sku.getSpec());//sku规格
            dataModel.put("specItems", specItems);
            Map<String, List> specMap = (Map) JSON.parseObject(spu.getSpecItems());
            for(String key: specMap.keySet()){
                List<String> list = specMap.get(key);
                List<Map> mapList=new ArrayList<>();
                for(String value:list ){//循环规格选项值
                    Map map=new HashMap();
                    map.put("option",value);
                    if(specItems.get(key).equals(value)){ //判断此规格组合是否是当前SKU的，标记选中状态
                        map.put("checked",true);
                    }else{
                        map.put("checked",false);
                    }

                    //当前的sku
                    Map<String, String> spec = (Map) JSON.parseObject(sku.getSpec());
                    spec.put(key, value);
                    String specJson = JSON.toJSONString(spec, SerializerFeature.MapSortField);
                    map.put("url", urlMap.get(specJson));

                    mapList.add(map);
                }
                specMap.put(key,mapList);//用新集合覆盖原集合

            }

            dataModel.put("specMap", specMap);


            context.setVariables(dataModel);

            //(2)准备文件
            File dir = new File(pagePath);
            if(!dir.exists()){
                dir.mkdirs();
            }
            File dest = new File(dir, sku.getId()+".html");

            //(3)生成页面
            try {
                PrintWriter writer = new PrintWriter(dest, "UTF-8");
                templateEngine.process("./src/main/resources/templates/item", context, writer);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

}
